package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.adapter.StickerAdapter;
import flc.ast.adapter.VideoStickerAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.ActivityGifMakeBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class GifMakeActivity extends BaseAc<ActivityGifMakeBinding> {

    public static String videoPath = "";
    private long videoLength;
    private int mFrame = 10;
    private float mSpeed = 1.0f;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
            }
            mHandler.postDelayed(this, 500);
        }
    };
    private ColorAdapter colorAdapter;
    private VideoStickerAdapter stickerAdapter;
    private int oldPosition = 0;
    private int videoWidth;
    private int videoHeight;

    @Override
    protected int onCreate() {
        return R.layout.activity_gif_make;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivGifMakeBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvGifMakeSave.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvText.setOnClickListener(this);
        mDataBinding.tvSticker.setOnClickListener(this);

        mDataBinding.rvTextColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvTextColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);

        mDataBinding.rvStickerList.setLayoutManager(new GridLayoutManager(mContext, 3));
        stickerAdapter = new VideoStickerAdapter();
        mDataBinding.rvStickerList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);

        mHandler = new Handler();
        mDataBinding.tvDuration.setText("00:00" + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(videoPath), getString(R.string.duration_style)));
                mDataBinding.ivPlay.setSelected(false);
                mp.seekTo(1);
                stopTime();
            }
        });

        mDataBinding.etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                mDataBinding.txtStickerView.setText(str);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == colorAdapter) {
            colorAdapter.getItem(oldPosition).setSelect(false);
            colorAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            colorAdapter.getItem(position).setSelect(true);
            colorAdapter.notifyItemChanged(position);
            mDataBinding.txtStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
        } else {
            //设置贴纸
            Resources res = getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getImg());
            mDataBinding.ivStickerView.addBitImage(bmp);
        }
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvGifMakeSave://保存
                saveVideo();
                break;
            case R.id.ivPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlay.setSelected(false);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlay.setSelected(true);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvText://文字
                mDataBinding.tvText.setBackgroundResource(R.drawable.xz3);
                mDataBinding.tvSticker.setBackground(null);
                mDataBinding.llText.setVisibility(View.VISIBLE);
                mDataBinding.llSticker.setVisibility(View.GONE);
                break;
            case R.id.tvSticker://贴纸
                mDataBinding.tvText.setBackground(null);
                mDataBinding.tvSticker.setBackgroundResource(R.drawable.xz3);
                mDataBinding.llText.setVisibility(View.GONE);
                mDataBinding.llSticker.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);

        mDataBinding.tvDuration.setText("00:00" + "/" + TimeUtils.millis2String(videoLength, getString(R.string.duration_style)));

        mHandler = new Handler();
        setSticker();

        //颜色数据
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#FFFFFF", true));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        colorAdapter.setList(listColor);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor("#FFFFFF"));

        //贴纸数据
        List<MyStickerBean> listSticker = new ArrayList<>();
        listSticker.add(new MyStickerBean(R.drawable.iv_tz1, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz2, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz3, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz4, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz5, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz6, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz7, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz8, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz9, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz10, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz11, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz12, false));
        stickerAdapter.setList(listSticker);
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_ing));
        mDataBinding.ivStickerView.setShowHelpToolFlag(false);
        mDataBinding.txtStickerView.setShowHelpBox(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<Boolean>() {
                    private String imagePath1, imagePath2;

                    @Override
                    public void doBackground(ObservableEmitter<Boolean> emitter) {
                        Bitmap bitmap1 = ImageUtils.view2Bitmap(mDataBinding.ivStickerView);
                        Bitmap bitmap2 = ImageUtils.view2Bitmap(mDataBinding.txtStickerView);
                        imagePath1 = FileUtil.generateFilePath(Content.MY_TEMP, ".png");
                        imagePath2 = FileUtil.generateFilePath(Content.MY_TEMP, ".png");
                        boolean save1 = ImageUtils.save(bitmap1, imagePath1, Bitmap.CompressFormat.PNG);
                        boolean save2 = ImageUtils.save(bitmap2, imagePath2, Bitmap.CompressFormat.PNG);
                        emitter.onNext(save2);
                    }

                    @Override
                    public void accept(Boolean isSave) {
                        if (isSave) {
                            EpDraw epDraw1 = new EpDraw(imagePath1, 0, 0, videoWidth, videoHeight, false);
                            EpDraw epDraw2 = new EpDraw(imagePath2, 0, 0, videoWidth, videoHeight, false);
                            epDraw1.setRotate(0);
                            epDraw2.setRotate(0);
                            String resultFile = FileUtil.generateFilePath(Content.MY_TEMP, ".mp4");
                            EpVideo epVideo = new EpVideo(videoPath);
                            epVideo.addDraw(epDraw1);
                            epVideo.addDraw(epDraw2);
                            EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                            EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                                @Override
                                public void onSuccess() {
                                    dismissDialog();
                                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            save(resultFile);
                                        }
                                    }, 100);
                                }

                                @Override
                                public void onFailure() {
                                    dismissDialog();
                                    ToastUtils.showShort(R.string.save_def);
                                }

                                @Override
                                public void onProgress(float progress) {
                                    showDialog(getString(R.string.save_ing));
                                }
                            });
                        }
                    }
                });
            }
        }, 500);
    }

    private void save(String videoPath) {
        int scaleWidth = mDataBinding.videoView.getWidth();
        int scaleHeight = mDataBinding.videoView.getHeight();
        if (scaleWidth * scaleHeight > 960 * 540) {
            //原视频分辨率过大，则要缩小一倍
            scaleWidth = scaleWidth / 2;
            scaleHeight = scaleHeight / 2;
        }
        showDialog(getString(R.string.ve_handle_percent_format, 0 + "%"));
        EditorHolder.editor().video2Gif(videoPath, scaleWidth, scaleHeight, mFrame, mSpeed, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                FileP2pUtil.copyPrivateImgToPublic(mContext, outFilePath);
                startActivity(HomeActivity.class);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.ve_covert_gif_fail_tip));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.ve_handle_percent_format, progress + "%"));
            }
        });
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.ivStickerView.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.ivStickerView.setLayoutParams(stickerLayoutParams);
                mDataBinding.txtStickerView.setLayoutParams(stickerLayoutParams);
            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTime();
    }

}